var showDateDom = $('#showDate');
// 初始化时间
var now = new Date();
var nowYear = now.getFullYear();
var nowMonth = now.getMonth() + 1;
var nowDate = now.getDate();
showDateDom.attr('data-year', nowYear);
showDateDom.attr('data-month', nowMonth);
showDateDom.attr('data-date', nowDate);
// 数据初始化
function formatYear (nowYear) {
    var arr = [];
    for (var i = nowYear - 100; i <= nowYear + 30; i++) {
        arr.push({
            id: i + '',
            value: i + '年'
        });
    }
    return arr;
}
function formatMonth () {
    var arr = [];
    for (var i = 1; i <= 12; i++) {
        arr.push({
            id: i + '',
            value: i + '月'
        });
    }
    return arr;
}
function formatDate (count) {
    var arr = [];
    for (var i = 1; i <= count; i++) {
        arr.push({
            id: i + '',
            value: i + '日'
        });
    }
    return arr;
}
var yearData = function(callback) {
        callback(formatYear(nowYear))
}
var monthData = function (year, callback) {
        callback(formatMonth());
};
var dateData = function (year, month, callback) {
    //setTimeout(function() {
        if (/^1|3|5|7|8|10|12$/.test(month)) {
            callback(formatDate(31));
        }
        else if (/^4|6|9|11$/.test(month)) {
            callback(formatDate(30));
        }
        else if (/^2$/.test(month)) {
            if (year % 4 === 0 && year % 100 !==0 || year % 400 === 0) {
                callback(formatDate(29));
            }
            else {
                callback(formatDate(28));
            }
        }
        else {
            throw new Error('month is illegal');
        }
};


function birthPicker(element){
	var $element = element.target;
	var oneLevelId = showDateDom.attr('data-year');
    var twoLevelId = showDateDom.attr('data-month');
    var threeLevelId = showDateDom.attr('data-date');
	var iosSelect = new IosSelect(3, 
	        [yearData, monthData, dateData],
	        {
	            title: '时间选择',
	            itemHeight: 35,
	            relation: [0,0,0,0],
	            oneLevelId: oneLevelId,
	            twoLevelId: twoLevelId,
	            threeLevelId: threeLevelId,
	            showLoading: true,
	            callback: function (selectOneObj, selectTwoObj, selectThreeObj) {
	            	if(selectTwoObj.id.length==1){
	            		selectTwoObj.id = "0"+selectTwoObj.id;
	            	}
	            	if(selectThreeObj.id.length==1){
	            		selectThreeObj.id = "0"+selectThreeObj.id;
	            	}
	            	var _name = $element.name;
	            	var _value = selectOneObj.id+"-"+selectTwoObj.id+"-"+selectThreeObj.id;
	            	$("#birthdayVal").html(_value);
	            	$("#birthday").val(_value);
	            }
	    });
}


function sureSex(){
		var sex = $("input[name='radio-2-set']:checked").val();
		if(sex=='0'){
			var sexVal = '男';
		}else if(sex=='1'){
			var sexVal = '女';
		}else{
			var sexVal = '';
		}
		$("#sexVal").html(sexVal);
		$("#sex").val(sex);
	}
function sureMarry(){
	var marriage = $("input[name='radio-3-set']:checked").val();
	if(marriage=='0'){
		var marriageVal = '单身';
	}else if(marriage=='1'){
		var marriageVal = '已婚';
	}else{
		var marriageVal = '已婚有子女';
	}
	$("#MarriageVal").html(marriageVal);
	$("#marriage").val(marriage);
}
function sureCounselor(){
	
	var counselor = $("input[name='radio-1-set']:checked").val();
	$("#counselorName").html(counselor);
}
//选择省市
function selectProvince(){
	 $("#mainDiv").hide();
	 $("#mainDiv").removeClass("active in");
	 $("#selectCity").hide();
	 $("#selectCity").removeClass("active in");
	 $("#selectProvince").show();
	 //初始化界面
	 $("#selectProvince").html("");
	 $("#selectProvince").addClass("active in");
	$.ajax({
		headers: {'Cookie' : document.cookie },
		method : 'get',
		url : rootPath+'/maintain/api/v1/maintainDealerMap?regionType=90011001',
		error:function(XMLHttpRequest, ajaxOptions, thrownError){
			//alert("数据刷新失败");
		},
		success : function(resultData){
			var wholeHtml = '<h3>省份选择</h3>';
			$.each(resultData,function(memberInfoIndex,memberInfoObj){
				var provinceHtml = '';
				
				provinceHtml = provinceHtml + '<a onclick="selectCity('+ memberInfoObj.regionCode +')" class="list-group-item">'+ memberInfoObj.regionName +'</a>'
											+ '<input class="hidden" id="'+ memberInfoObj.regionCode +'" value="'+ memberInfoObj.regionName +'">'
				
			    wholeHtml += provinceHtml;
			});
			
			$("#selectProvince").append(wholeHtml);
		}
	});
}
//选择城市
function selectCity(obj){
	 $("#provinceCode").val(obj);
	 $("#mainDiv").hide();
	 $("#mainDiv").removeClass("active in");
	 $("#selectProvince").hide();
	 $("#selectProvince").removeClass("active in");
	 $("#selectCity").show();
	 //初始化界面
	 $("#selectCity").html("");
	 $("#selectCity").addClass("active in");
	 $("#province").html($("#"+obj).val());
	$.ajax({
		headers: {'Cookie' : document.cookie },
		method : 'get',
		url : rootPath+'/maintain/api/v1/SelectCityMap?parentCode='+obj,
		error:function(XMLHttpRequest, ajaxOptions, thrownError){
			//alert("数据刷新失败");
		},
		success : function(resultData){
			var wholeHtml = '<h3>城市选择</h3>';
			$.each(resultData,function(memberInfoIndex,memberInfoObj){
				var cityHtml = '';
				
				cityHtml = cityHtml + '<a onclick="sureCity('+ memberInfoObj.regionCode +')" class="list-group-item">'+ memberInfoObj.regionName +'</a>'
									+ '<input class="hidden" id="'+ memberInfoObj.regionCode +'" value="'+ memberInfoObj.regionName +'">'
											
			    wholeHtml += cityHtml;
			});
			
			$("#selectCity").append(wholeHtml);
		}
	});
}
//确认城市
function sureCity(obj){
	 $("#cityCode").val(obj);
	 $("#selectCity").hide();
	 $("#selectCity").removeClass("active in");
	 $("#selectProvince").hide();
	 $("#selectProvince").removeClass("active in");
	 $("#mainDiv").show();
	 //初始化界面
	 $("#mainDiv").addClass("active in");
	 $("#city").html($("#"+obj).val());
	 if($("#city").html()==$("#province").html()){
			$("#city").html("");
		 }
}
//选择养修预约时间，点击
function selectMaintainTime(obj){
	 $("#mainDiv").hide();
	 $("#mainDiv").removeClass("active in");
	 $("#maintainDateSelDiv").show();
	 //初始化界面
	 $("#maintainDateSelDiv").addClass("active in");
	 
}
//选择保养日期，时间之后确认
function confirmMaintainTime(obj) {

	//$("#selectMaintainTimeSpan").val("#ss").val();
	$("#mainDiv").show();
	$("#mainDiv").addClass("active in");
	$("#maintainDateSelDiv").removeClass("active in");
	$("#maintainDateSelDiv").hide();
	
	$("#birthdayVal").html($("#day").html());
	$("#birthday").val($("#birthdayVal").html());
	//$("#maintainDate").val($("#day").html());
	//$("#maintainTime").val($("#time").html());
}
//顾问ID
function seCounselor(obj){
	$("#userId").val(obj);
}

$(document).ready(function(){
	$("#KmFirst").hide();
	var rootPath = getRootPath();
	
	var dealerCode= getQueryParamValue("dealerCode");
	//监听城市选择页面搜索输入框
	$("#cha").keyup(function(event){ 
        if (event.keyCode === 13){ 
       	 searchCity();
        } 
      }); 
	
	//监听经销商选择页面搜索输入框
	$("#sou").keyup(function(event){ 
        if (event.keyCode === 13){ 
       	 searchDealer();
        } 
      }); 

	$("#mtDate").hide();
	
	$("#selectSex").click(function(){
		$('#sexModal').modal({
			keyboard: false,
			backdrop:false
		});
	});
	$("#selectMarriage").click(function(){
		$('#MarriageModal').modal({
			keyboard: false,
			backdrop:false
		});
	});
	$("#selectSexCounselor").click(function(){
		$('#counselorModal').modal({
			keyboard: false,
			backdrop:false
		});
	});
	

	
	$.ajax({
		headers: {'Cookie' : document.cookie },
		method : 'get',
		url : rootPath+'/customer/api/v1/customerInfo',
		error:function(XMLHttpRequest, ajaxOptions, thrownError){
			//alert("数据刷新失败");
		},
		success : function(resultData){
			$.each(resultData,function(memberInfoIndex,memberInfoObj){
				var userId = memberInfoObj.userId;
				if(userId==null||userId==""){
					//非会员，隐藏保存按钮
					$("#immediatelyAppoint").hide();
				}
				if(memberInfoObj.sex=='0'){var sex = '男';}
				else if(memberInfoObj.sex=='1'){var sex='女';}
				else{var sex=' '}
				$("#counselorName").html(memberInfoObj.saleName);
				$("#potentialUserId").val(memberInfoObj.potentialUserId);
				$("#Imgurl").attr('src',memberInfoObj.headImgurl);
				$("#userName").val(memberInfoObj.nickName);
				$("#carOwnerId").val(memberInfoObj.userId);
				$("#phone").html(memberInfoObj.phone);
				$("#birthdayVal").html(memberInfoObj.birthday);
				$("#sex").val(memberInfoObj.sex);
				$("#sexVal").html(sex);
				$("#address").val(memberInfoObj.address);
				$("#dealerName").html(memberInfoObj.dealerShortName);
				$("#city").html(memberInfoObj.city);
				$("#province").html(memberInfoObj.province);
				$("#cityCode").val(memberInfoObj.cityCode);
				$("#provinceCode").val(memberInfoObj.provinceCode);
				//$("#counselorName").html(memberInfoObj.counselorName);
				$("#userId").val(memberInfoObj.counselopId);
				$("#dealerCode").val(memberInfoObj.dealerCode);
			});
		}
	});
	// 保存确定按钮
	$("#immediatelyAppoint").click(function(){
		
		var CarOwnerDto ={"userName":$("#userName").val(),"birthday":$("#birthday").val(),"sex":$("#sex").val(),"marriage":$("#marriage").val(),
						  "address":$("#address").val(),"userId":$("#carOwnerId").val(),"phone":$("#phone").html(),
						  "city":$("#cityCode").val(),"province":$("#provinceCode").val()
		}
		var PotentialDto ={"dealerCode":$("#dealerCode").val(),"potentialUserId":$("#potentialUserId").val()
		}
		var CounselorDto ={"tmUsersId":$("#salesConsultantId").val(),"potentialUserId":$("#potentialUserId").val()
		}
		$.ajax({ 
			headers: {'Cookie' : document.cookie },
		    type:"POST", 
		    url:rootPath+"/customer/api/v1/updateCarOwnerInfo", 
		    dataType:"json",      
		    contentType:"application/json",               
		    data:JSON.stringify(CarOwnerDto), 
		    success:function(data){ 
		    	$.ajax({ 
		    		headers: {'Cookie' : document.cookie },
				    type:"POST", 
				    url:rootPath+"/customer/api/v1/updatePotentialInfo", 
				    dataType:"json",      
				    contentType:"application/json",               
				    data:JSON.stringify(PotentialDto), 
				    success:function(data){ 
				    	$.ajax({ 
				    		headers: {'Cookie' : document.cookie },
						    type:"POST", 
						    url:rootPath+"/customer/api/v1/updateCounselorInfo", 
						    dataType:"json",      
						    contentType:"application/json",               
						    data:JSON.stringify(CounselorDto), 
						    success:function(data){ 
								alert("保存成功");
								window.location = "http://carowner.yonyouauto.com/wx/pub/personal?WECHAT_USER_OPENID="+getCookie("WECHAT_USER_OPENID");
						    },
						    error:function(data){
						    	//alert("保存失败！");
						    }
						  });
				    	
				    },
				    error:function(data){
				    	//alert("保存失败！");
				    }
				  });
		    	
		    },
		    error:function(data){
		    	//alert("保存失败！");
		    }
		  });
		});
})
//定位所在定经销商,二级页面
function selectNowDealer(obj){
	 $("#sou").val("");
	 $("#headImg").hide();
	 $("#mainDiv").hide();
	 $("#mainDiv").removeClass("active in");
	 $("#maintainDealerDiv").hide();
	 $("#maintainDealerDiv").removeClass("active in");
	 $("#nowDealerDiv").show();
	 $("#dealerDiv").html("");
	 //初始化界面
	 $("#nowDealerDiv").addClass("active in");
		//根据城市名获取所在地经销商列表
			$.ajax({
				headers: {'Cookie' : document.cookie },
				method : 'get',
				url : rootPath+'/maintain/api/v1/maintainDealer?regionName='+ $("#regionName").val()+'&dealerCode='+dealerCode,
				error:function(XMLHttpRequest, ajaxOptions, thrownError){
					//alert("未连接服务器!");
				},
				success : function(resultData){
					
					var wholeHtml = '';
					var  Km = '';
					$.each(resultData,function(maintainDealerIndex,maintainDealerObj){
						
						var findDealerHtml = '';
						var lat1 = maintainDealerObj.latitude;
						var lng1 = maintainDealerObj.longitude;
						var lat2 = $("#latitude").val();
						var lng2 = $("#longitude").val();
						Km = GetDistance(lat1,lng1,lat2,lng2).toFixed(2);
						if(lat1==null||lat1=="0"||lng1==null||lng1=="0"){var distance = "暂无";}
						else{var distance = Km + '千米';}
						
							if(maintainDealerObj.remark =='首选店'){
								$("#KmFirst").show();
								$("#nameFirst").html(maintainDealerObj.dealerShortName);
								$("#distanceFirst").html(distance);
								$("#addrFirst").html(maintainDealerObj.detailAddress);
								$("#codeFirst").val(maintainDealerObj.dealerCode);
								$("#shortNameFirst").html(maintainDealerObj.dealerShortName);
								$('#Tel').attr('href','tel:'+maintainDealerObj.serviceHotline);
								$("#remarkFirst").html(maintainDealerObj.remark);
							}else{
						findDealerHtml = findDealerHtml + '<li data-id="'+ Km +'">'
														+ '<div class="panel panel-default">'
														+ '<table style="width:100%" class="table-condensed"><tbody>'
														+ '<tr>'
														+ '<td style="width:160px;text-align:left;"><a onclick="sureDealer('+maintainDealerIndex+')">'
														+ '<p id="name'+ maintainDealerIndex +'" style="font-family:黑体;font-size:16px;color:#000000">' + maintainDealerObj.dealerShortName + '</p>'
														+ '<p class="hidden" id="shortName'+maintainDealerIndex+'">'+maintainDealerObj.dealerShortName+'</p>'
														+ '</a></td>'
														+ '<td style="width:100px;text-align:center;font-size:14px;color:#7a7a7a">'
														+ '<span>距离：</span><span>'+ distance + '</span>'
														+ '</td>'
														+ '</tr><tr>'
														+ '<td style="width:160px;text-align:left;">'
														+ '<span id="addr'+ maintainDealerIndex +'" style="font-faminly:宋体;font-size:15px;color:#615f5f">' + maintainDealerObj.detailAddress + '</span>'
														+ '</td>'
														+ '<td style="width:100px;text-align:center;">'
														+ '<a href="tel:'+ maintainDealerObj.serviceHotline +'" id="Tel">'
														+ '<span class="glyphicon glyphicon-earphone" style="color: rgb(255, 0, 23); font-size: 12px;"></span>'
														+ '<span style="font-family:宋体;font-size:14px;color:#7a7a7a"> 电话</span>'
														+ '</a></td>'
														+ '</tr>'
														+ '</tbody></table>'
														+ '<input id="code'+ maintainDealerIndex +'" class="hidden" value="' + maintainDealerObj.dealerCode + '">'
														+ '</div></li>'
						
						wholeHtml += findDealerHtml;
						}
					});
					$("#dealerDiv").append(wholeHtml);
				}
			});
			
}
//选择经销商，点击
function selectMaintainDealer(obj){
	$("#cha").val("");
	$("#dealerMap").show();
	$("#KmFirst").hide();
	$("#headImg").hide();
	$("#mainDiv").hide();
	$("#mainDiv").removeClass("active in");
	$("#nowDealerDiv").hide();
	$("#nowDealerDiv").removeClass("active in");
	 $("#maintainDealerDiv").show();
	 //初始化界面
	 $("#maintainDealerDiv").addClass("active in");
		
		// 选择经销商城市信息取得。
		$.ajax({
			headers: {'Cookie' : document.cookie },
			method : 'get',
			url : rootPath+'/maintain/api/v1/maintainDealerMap?regionType=90011002',
			error:function(XMLHttpRequest, ajaxOptions, thrownError){
				//alert("获取失败!");
			},
			success : function(resultData){

				var wholeHtml = '';
				
				var city = '';
				$.each(resultData,function(maintainDealerMapIndex,maintainDealerMapObj){
					var DealerMapHtml = '';
					var str = maintainDealerMapObj.regionName;
					if(str == "") return;
					var arr = maintainDealerMapObj.aleph;
					for(var i=0;i<26;i++){
						var en = String.fromCharCode((97+i));
						if(arr == en){
							city = maintainDealerMapObj.regionName;

							DealerMapHtml = DealerMapHtml + '<li>'
														  + '<a onclick="selectDealer('+ maintainDealerMapIndex +')">'
														  + '<span style="font-size:18px;color:#7a7a7a">' + city + '</span>'
														  + '<input type="hidden" id="'+maintainDealerMapIndex + '" value="'+ maintainDealerMapObj.regionName +'">'
														  + '</a>'
														  + '</li>'
														  + '<div style="height:1px;margin:0px auto;padding:0px;background-color:#F4F4F4;overflow:hidden;"></div>'
							
							$("#"+en).append(DealerMapHtml);
						}
					}
				});

			}
		});		
}
//城市进入该城市经销商
function selectDealer(obj){
	$("#sou").val("");
	var code = $("#"+obj).val();
	$("#regionName").val(code);
	$("#headImg").hide();
	$("#mainDiv").hide();
	$("#mainDiv").removeClass("active in");
	$("#maintainDealerDiv").hide();
	$("#maintainDealerDiv").removeClass("active in");
	$("#dealerDiv").html("");
	 $("#nowDealerDiv").show();
	 $("#searchCity").html("");
	 $("#searchDealer").html("");
	 $("#list2").show();
	 //初始化界面
	 $("#nowDealerDiv").addClass("active in");
	 for(var i=0;i<26;i++){
			var en = String.fromCharCode((97+i));
			$("#"+en).html("");
	 }
	//根据编号获取所在地经销商列表
	$.ajax({
		headers: {'Cookie' : document.cookie },
		method : 'get',
		url : rootPath+'/maintain/api/v1/maintainDealer?regionName='+code+'&dealerCode='+$("#dealerCode").val(),
		error:function(XMLHttpRequest, ajaxOptions, thrownError){
			//alert("未连接服务器!");
		},
		success : function(resultData){
			
			var wholeHtml = '';
			var  Km = '';
			$.each(resultData,function(maintainDealerIndex,maintainDealerObj){
				
				var findDealerHtml = '';
				var lat1 = maintainDealerObj.latitude;
				var lng1 = maintainDealerObj.longitude;
				var lat2 = $("#latitude").val();
				var lng2 = $("#longitude").val();
				Km = GetDistance(lat1,lng1,lat2,lng2).toFixed(2);
				if(lat1==null||lat1=="0"||lng1==null||lng1=="0"){var distance = "暂无";}
				else{var distance = Km + '千米';}
				
				findDealerHtml = findDealerHtml + '<li data-id="'+ Km +'">'
												+ '<div class="panel panel-default">'
												+ '<table style="width:100%" class="table-condensed"><tbody>'
												+ '<tr>'
												+ '<td style="width:160px;text-align:left;"><a onclick="sureDealer('+maintainDealerIndex+')">'
												+ '<p id="name'+ maintainDealerIndex +'" style="font-family:黑体;font-size:16px;color:#000000">' + maintainDealerObj.dealerShortName + '</p>'
												+ '<p class="hidden" id="shortName'+maintainDealerIndex+'">'+maintainDealerObj.dealerShortName+'</p>'
												+ '</a></td>'
												+ '<td style="width:100px;text-align:center;font-size:14px;color:#7a7a7a">'
												+ '<span>距离：</span><span>'+ distance + '</span>'
												+ '</td>'
												+ '</tr><tr>'
												+ '<td style="width:160px;text-align:left;">'
												+ '<span id="addr'+ maintainDealerIndex +'" style="font-faminly:宋体;font-size:15px;color:#615f5f">' + maintainDealerObj.detailAddress + '</span>'
												+ '</td>'
												+ '<td style="width:100px;text-align:center;">'
												+ '<a href="tel:'+ maintainDealerObj.serviceHotline +'" id="Tel">'
												+ '<span class="glyphicon glyphicon-earphone" style="color: rgb(255, 0, 23); font-size: 12px;"></span>'
												+ '<span style="font-family:宋体;font-size:14px;color:#7a7a7a"> 电话</span>'
												+ '</a></td>'
												+ '</tr>'
												+ '</tbody></table>'
												+ '<input id="code'+ maintainDealerIndex +'" class="hidden" value="' + maintainDealerObj.dealerCode + '">'
												+ '</div></li>'
				
				wholeHtml += findDealerHtml;
			});
			$("#dealerDiv").append(wholeHtml);
		}
	});
}
//选中某经销商
function sureDealer(obj){
	if(obj=='-1'){
	  var code = $("#codeFirst").val();
 	  var name = $("#shortNameFirst").html();
   	  var addr = $("#addrFirst").html();
	}else{
	  var code = $("#code"+obj).val();
	  var name = $("#shortName"+obj).html();
	  var addr = $("#addr"+obj).html();
	}
	//alert(code+','+name+','+addr);
	$("#dealerCode").val(code);
	$("#dealerName").html(name);
	//$("#detailAddress").html(addr);
	$("#nowDealerDiv").hide();
	$("#nowDealerDiv").removeClass("active in");
	 $("#mainDiv").show();
	 //初始化界面
	 $("#mainDiv").addClass("active in");
	 $("#headImg").show();
	 $("#list2").show();
	 $("#searchDealer").html("");
}
//排序
function Sort(bo)
{
    var arr = document.getElementById("list2").innerHTML.match(/<li>[\s\S]+?<\/li>/g);
    arr.sort(function(a,b){
        a = parseInt(/\d+/.exec(a)[0], 10);
        b = parseInt(/\d+/.exec(b)[0], 10);
        return bo?b-a:a-b;
    });
    document.getElementById("ol1").innerHTML = arr.join("");
}
//进行经纬度转换为距离的计算
function Rad(d){
  return d * Math.PI / 180.0;//经纬度转换成三角函数中度分表形式。
}
//计算距离，参数分别为第一点的纬度，经度；第二点的纬度，经度
function GetDistance(lat1,lng1,lat2,lng2){

   var radLat1 = Rad(lat1);
   var radLat2 = Rad(lat2);
   var a = radLat1 - radLat2;
   var  b = Rad(lng1) - Rad(lng2);
   var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) +
   Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
   s = s *6378.137 ;// EARTH_RADIUS;
   s = Math.round(s * 10000) / 10000; //输出为公里
   //s=s.toFixed(4);
   return s;
}
//搜索城市
function searchCity(){
	$("#dealerMap").hide();
	$("#searchCity").html("");
	var regionName = $("#cha").val();
	$.ajax({
		headers: {'Cookie' : document.cookie },
	    type:"GET", 
	    url:rootPath+"/maintain/api/v1/maintainSelectCity?regionName="+regionName, 
	    dataType:"json",      
	    async: false,
	    contentType:"application/json",               
	    data:null, 
	    success:function(data){ 
			var wholeHtml = '<ul class="list-group">';
			
			$.each(data,function(maintainSearchCityIndex,maintainSearchCityObj){
				var DealerMapHtml = '';
				
					DealerMapHtml = DealerMapHtml   + '<li class="list-group-item">'
													+ '<a onclick="selectDealer('+ maintainSearchCityIndex +')">'
													+ '<span style="font-size:18px;color:#7a7a7a">' + maintainSearchCityObj.regionName + '</span>'
													+ '<input type="hidden" id="'+maintainSearchCityIndex + '" value="'+ maintainSearchCityObj.regionName +'">'
													+ '</a>'
													+ '</li>'		
				       wholeHtml += DealerMapHtml;
			});
			wholeHtml = wholeHtml + '</ul>'
			$("#searchCity").append(wholeHtml);
	    },
	    error:function(data){
	    	//alert("数据刷新失败，请联系管理员！");
	    }
	 });
}
//搜索经销商
function searchDealer(){
	$("#list2").hide();
	$("#searchDealer").html("");
	var dealerName = $("#sou").val();
	var regionName = $("#regionName").val();
	$.ajax({
		headers: {'Cookie' : document.cookie },
	    type:"GET", 
	    url:rootPath+"/maintain/api/v1/searchDealer?dealerName="+dealerName, 
	    dataType:"json",      
	    async: false,
	    contentType:"application/json",               
	    data:null, 
	    success:function(data){ 
			var wholeHtml = '<ul class="list-group">';
			var  Km = '';
			$.each(data,function(SearchDealerIndex,SearchDealerObj){
				var DealerMapHtml = '';
				var findDealerHtml = '';
				var lat1 = SearchDealerObj.latitude;
				var lng1 = SearchDealerObj.longitude;
				var lat2 = $("#latitude").val();
				var lng2 = $("#longitude").val();
				Km = GetDistance(lat1,lng1,lat2,lng2).toFixed(2);
				if(lat1==null||lat1=="0"||lng1==null||lng1=="0"){var distance = "暂无";}
				else{var distance = Km + '千米';}
				
					DealerMapHtml = DealerMapHtml   + '<li class="list-group-item">'
													+ '<table style="width:100%" class="table-condensed"><tbody>'
													+ '<tr>'
													+ '<td style="width:160px;text-align:left;"><a onclick="sureDealer('+SearchDealerIndex+')">'
													+ '<p id="name'+ SearchDealerIndex +'" style="font-family:黑体;font-size:16px;color:#000000">' + SearchDealerObj.dealerShortName + '</p>'
													+ '<p class="hidden" id="shortName'+SearchDealerIndex+'">'+SearchDealerObj.dealerShortName+'</p>'
													+ '</a></td>'
													+ '<td style="width:100px;text-align:center;font-size:14px;color:#7a7a7a">'
													+ '<span>距离：</span><span>'+ distance + '</span>'
													+ '</td>'
													+ '</tr><tr>'
													+ '<td style="width:160px;text-align:left;">'
													+ '<span id="addr'+ SearchDealerIndex +'" style="font-faminly:宋体;font-size:15px;color:#615f5f">' + SearchDealerObj.detailAddress + '</span>'
													+ '</td>'
													+ '<td style="width:100px;text-align:center;">'
													+ '<a href="tel:'+ SearchDealerObj.serviceHotline +'" id="Tel">'
													+ '<span class="glyphicon glyphicon-earphone" style="color: rgb(255, 0, 23); font-size: 12px;"></span>'
													+ '<span style="font-family:宋体;font-size:14px;color:#7a7a7a"> 电话</span>'
													+ '</a></td>'
													+ '</tr>'
													+ '</tbody></table>'
													+ '<input id="code'+ SearchDealerIndex +'" class="hidden" value="' + SearchDealerObj.dealerCode + '">'
													+ '</li>'
											
					wholeHtml += DealerMapHtml;
			});
			wholeHtml = wholeHtml + '</ul>'
			$("#searchDealer").append(wholeHtml);
	    },
	    error:function(data){
	    	//alert("数据刷新失败，请联系管理员！");
	    }
	 });
}
//服务顾问选择
function selectCounselor(){
	$("#seviceUser").html("");
	//服务顾问信息取得
	$.ajax({
		headers: {'Cookie' : document.cookie },
	    type:"GET", 
	    url:rootPath+"/customer/api/v1/counselors?positionId=602&dealerCode="+$("#dealerCode").val(), 
	    dataType:"json",      
	    async: false,
	    contentType:"application/json",               
	    data:null, 
	    success:function(data){ 
			var wholeHtml = '';
			$.each(data,function(carModelIndex,advisersObj){
				var counselorsHtml = '';
				
				counselorsHtml = counselorsHtml + '<div class="radio" onclick="addCounseor('+carModelIndex+')">'
												+ '<label>'
												+ '<input name="SelRadio" type="radio" id="coun'+carModelIndex+'" value="'+advisersObj.userName+'">'+advisersObj.userName
												+ '<input class="hidden" type="text" id="salePhone'+carModelIndex+'" value="'+advisersObj.phone+'">'
												+ '<input class="hidden" type="text" id="saleUserId'+carModelIndex+'" value="'+advisersObj.userId+'">'
												+ '</label>'
												+ '</div>'

				wholeHtml += counselorsHtml;								
			});
			$("#seviceUser").append(wholeHtml);
	    },
	    error:function(data){
	    	//alert("数据刷新失败，请联系管理员！");
	    }
	 });
	
	$('#counselorModal').modal({
	});
};
function addCounseor(obj){
	//alert(obj);
	$("#salesConsultantPhone").val($("#salePhone"+obj).val());
	$("#salesConsultantId").val($("#saleUserId"+obj).val());
	//$("#Counselor").html($("#seviceUser").find("option:selected").attr("userName"));
	$("#counselorName").html($("#coun"+obj).val());
	$("#conselorBtn").click();
};
function getCookie(cookie_name) {
	var allcookies = document.cookie;
	var cookie_pos = allcookies.indexOf(cookie_name);

	// 如果找到了索引，就代表cookie存在，
	// 反之，就说明不存在。
	if (cookie_pos != -1) {
		// 把cookie_pos放在值的开始，只要给值加1即可。
		cookie_pos += cookie_name.length + 1;
		var cookie_end = allcookies.indexOf(";", cookie_pos);

		if (cookie_end == -1) {
			cookie_end = allcookies.length;
		}

		var value = unescape(allcookies.substring(cookie_pos, cookie_end));
	}

	return value;
}
